package com.andox.fn.inf.rpc.rest.protocol.registry.zookeeper;

import java.util.List;
import java.util.Map;

import com.andox.fn.inf.rpc.rest.config.InterfaceConfig;
import com.andox.fn.inf.rpc.rest.config.ReferenceConfig;
import com.andox.fn.inf.rpc.rest.config.ServiceConfig;
import com.andox.fn.inf.rpc.rest.extension.ExtensionLoader;
import com.andox.fn.inf.rpc.rest.protocol.registry.AbstractRegistryService;
import com.andox.fn.inf.rpc.rest.protocol.registry.RegistryImpl;
import com.andox.fn.inf.rpc.rest.util.RegistryUtil;
import com.google.common.collect.Maps;


/**   
 * @ClassName:   ZookeeperRegistryService   
 * @author:      Andox
 * @date:        2019年8月16日 下午4:04:57   
 *     
 */
public class ZookeeperRegistryService extends AbstractRegistryService {

	private Map<String, RegistryImpl> registryImplTable = Maps.newHashMap();
	
	@Override
	public void start() {
	}

	@Override
	public void close() {

	}

	@Override
	protected List<ReferenceConfig> doSubsribe(ReferenceConfig referenceConfig, RegistryNotify rn) {
		return this.findRegistryImpl(referenceConfig).subscribe(referenceConfig, rn);
	}

	@Override
	protected void doUnsubsribe(ReferenceConfig referenceConfig) {
		this.findRegistryImpl(referenceConfig).unsubscribe(referenceConfig);
	}

	@Override
	protected void doRegister(ServiceConfig serviceConfig) {
		this.findRegistryImpl(serviceConfig).register(serviceConfig);
	}

	@Override
	protected void doUnregister(ServiceConfig serviceConfig) {
		this.findRegistryImpl(serviceConfig).unregister(serviceConfig);
	}
	
	private RegistryImpl findRegistryImpl(InterfaceConfig ic) {
		if (!this.registryImplTable.containsKey(ic.getRegistry())){
			synchronized (this) {
				if (!this.registryImplTable.containsKey(ic.getRegistry())){
					String protocol = RegistryUtil.findRegistryProtocol(ic.getRegistry());
					RegistryImpl registryImpl = ExtensionLoader.getExtensionLoader(RegistryImpl.class).getExtension(protocol);
					registryImpl.setConnection(ic.getRegistry());
					registryImpl.start();
				}
			}
		}
		
		return this.registryImplTable.get(ic.getRegistry());
	}
}
